#include "numbers.h"
#include <stdlib.h>

CxNumbers::CxNumbers(void)
{
	m_numbers = NULL;
	m_capacity = m_n = m_fixedN = 0;
	m_cs = new CxSection();
}

CxNumbers::~CxNumbers()
{
	delete m_cs;
	if(m_numbers != NULL) {
		delete[] m_numbers;
	}
}

void CxNumbers::Update(int numbers[], DWORD n)
{
	m_cs->Enter();
	if(n == 0) {
		m_n = m_fixedN = 0;
	}
	else {
		if(m_capacity < n) {
			if(m_numbers != NULL) {
				delete[] m_numbers;
			}
			m_capacity = (n/16+1) * 16;
			m_numbers = new int[m_capacity];
		}

		memcpy(m_numbers, numbers, sizeof(int)*n);
		m_n = m_fixedN = n;
	}
	m_cs->Leave();
}

void CxNumbers::AddTemp(int aNumber)
{
	m_cs->Enter();
	if(m_capacity < m_n+1) {
		m_capacity = ((m_n+1)/16+1) * 16;
		int* newNumbers = new int[m_capacity];
		if(m_numbers != NULL) {
			memcpy(newNumbers, m_numbers, sizeof(int)*m_n);
			delete[] m_numbers;
		}
		m_numbers = newNumbers;
	}
	m_numbers[m_n++] = aNumber;
	m_cs->Leave();
}

void CxNumbers::RemoveTemp(void)
{
	m_cs->Enter();
	m_n = m_fixedN;
	m_cs->Leave();
}

BOOL CxNumbers::Has(int number)
{
	BOOL has = FALSE;
	m_cs->Enter();
	for(DWORD i=0; i<m_n;i++) {
		if(number == m_numbers[i]) {
			has = TRUE;
			break;
		}
	}
	m_cs->Leave();
	return(has);
}
